﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using JCTimes.DomainModel.Repository;
using JCTimes.Portal.Infrastructure;
using JCTimes.Portal.Models;
using System.Collections.Generic;
using JCTimes.DomainModel.Entity;

namespace JCTimes.Portal.Controllers
{
    [Permission]
    public class FunctionsController : Controller {
        private IFunctionsRepository funcRep = null;
        private IFunctionRoleRepository frRep = null;
        private const int pageSize = 10;
        public FunctionsController(IFunctionsRepository funcRep,
                IFunctionRoleRepository frRep) {
            this.funcRep = funcRep;
            this.frRep = frRep;
        }

        /// <summary>
        /// Display menu in master page.
        /// </summary>
        /// <returns>Menu.</returns>
        //[ChildActionOnly]
        [SessionAllowed]
        public PartialViewResult Menu() {
            List<MenuItem> model = new List<MenuItem>();

            var currUser = SessionHelper.CurrUser;
            var funcs = funcRep.GetMenu(currUser.UserID, currUser.RoleID).ToList();

            #region sitepath

            string url = SessionHelper.Get("url");
            string sitePath = "";
            Function curFunc = funcRep.Find(f => f.URL == url);
            if (curFunc != null) {
                sitePath = GetSitePath(curFunc);
            }
            SessionHelper.SetSession("SitePath", sitePath);
            #endregion sitepath

            MenuItem menu = null;
            foreach (var top in funcs.Where(f => f.ParentID == null)) {
                menu = new MenuItem { MenuName = top.FunctionName };
                menu.ChildMenu = new List<MenuItem>();
                foreach (var child in funcs.Where(f => f.ParentID == top.ID)) {
                    menu.ChildMenu.Add(new MenuItem {
                        MenuName = child.FunctionName,
                        URL = child.URL,
                        Selected = (child.URL == url)
                    });
                }
                model.Add(menu);
            }

            return PartialView(model);
        }

        /// <summary>
        /// Get site path by current page.
        /// </summary>
        /// <param name="func">Current page's function</param>
        /// <returns>Site path.</returns>
        private string GetSitePath(Function func) {
            string parentID = func.ParentID;
            if (parentID != null) {
                return GetSitePath(funcRep.Find(parentID)) + ">>" + func.FunctionName;
            } else {
                return "";
            }
        }
    }
}